/**
 * 
 */
package com.antilia.infomaresme.config.modules;

import java.io.Serializable;
import java.util.Date;

import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;

import com.antilia.infomaresme.InfomaresmeApplication;
import com.antilia.infomaresme.data.dataobjects.Item;
import com.antilia.infomaresme.data.dataobjects.ItemEventSubject;

/**
 * @author Ernesto Reinaldo Barreiro
 *
 */
public class EventsInterceptor extends EmptyInterceptor {

		private static final long serialVersionUID = 1L;

	/**
	 * 
	 */
	public EventsInterceptor() {
	}
	
	@Override
	public boolean onFlushDirty(Object entity, Serializable id,
		Object[] currentState, Object[] previousState,
		String[] propertyNames, Type[] types) {
		if(entity instanceof Item) {
			Item item = (Item)entity;
			manageItem(item, id, currentState, previousState, propertyNames, types);			
		}
		return false;
	}
	
	
	
	/**
	 * Manage items changes.
	 * 
	 * @param item
	 * @param id
	 * @param currentState
	 * @param previousState
	 * @param propertyNames
	 * @param types
	 */
	protected void manageItem(Item item, Serializable id,
		Object[] currentState, Object[] previousState,
		String[] propertyNames, Type[] types ) {
		int index = 0;
		for(String property: propertyNames) {
			if(property.equals("price")) {
				ItemEventSubject eventSubject = ItemEventSubject.price_up;
				Double oldValue = (Double)previousState[index];
				Double newValue = (Double)currentState[index];
				if(oldValue == null && newValue!= null) {
					eventSubject = ItemEventSubject.price_up;
				} else if((newValue == null && oldValue.doubleValue()>=0)
						||(newValue !=null  && newValue.doubleValue() < oldValue.doubleValue())) {
					eventSubject = ItemEventSubject.price_down;
				}												
				InfomaresmeApplication.getQAApplication().getEventsDao().registerEvent(item, 
						eventSubject, oldValue!=null?oldValue.toString():"NO_PRICE", 
						newValue!=null?newValue.toString():"NO_PRICE");
			} 
			if(property.equals("date")) {
				ItemEventSubject eventSubject = ItemEventSubject.date_changed;
				Date oldValue = (Date)previousState[index];
				Date newValue = (Date)currentState[index];
				InfomaresmeApplication.getQAApplication().getEventsDao().registerEvent(item, 
						eventSubject, oldValue!=null?oldValue.toString():"NO_DATE", 
						newValue!=null?newValue.toString():"NO_DATE");
			}
			index++;
		}
	}	

}
